package com.household.security.filter;

import com.household.constant.SecurityConstant;
import com.household.domain.ResponseResult;
import com.household.domain.enums.ResponseErrorCodeEnum;
import com.household.security.exception.KaptchaNotMatchException;


import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.ObjectUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created By wanzhen
 * 2023. 2023/3/25. 14:25
 */
public class MyLoginFilter extends UsernamePasswordAuthenticationFilter {
    public static final String FORM_KAPTCHA_KEY="kaptcha";

    private String kaptchaParameter=FORM_KAPTCHA_KEY;

    public String getKaptchaParameter() {
        return kaptchaParameter;
    }

    public void setKaptchaParameter(String kaptchaParameter) {
        this.kaptchaParameter = kaptchaParameter;
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if (!request.getMethod().equals("POST")){
            throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
        }
        String username = request.getParameter(getUsernameParameter());
        String password = request.getParameter(getPasswordParameter());
        String kaptcha = request.getParameter(getKaptchaParameter());
        String kaptcha1 = (String)request.getSession().getAttribute("kaptcha");

        if (!ObjectUtils.isEmpty(kaptcha)&&!ObjectUtils.isEmpty(kaptcha1)&&kaptcha.equalsIgnoreCase(kaptcha1)){
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
            setDetails(request,authRequest);
            return this.getAuthenticationManager().authenticate(authRequest);
        }
        HttpSession session=request.getSession();
        session.setAttribute(SecurityConstant.LAST_EXCEPTION, ResponseResult.failure(ResponseErrorCodeEnum.VERIFY_CODE_ERROR));
        throw new KaptchaNotMatchException("验证码不匹配！");

    }
}
